/*
 * Copyright (c) 2008-2009 Daniel Freitas
 *
 * This file is part of Army Creator.
 *
 * Army Creator is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Army Creator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Army Creator.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.googlecode.armycreator.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Starts a {@link ServerSocket} to listen on port 3380 for shutdown messages. It will continuously monitor the socket
 * and fire a {@link ShutdownMonitor#shutdownMessageReceived()} if the socket reads the string "SUTDOWN".
 * <p/>
 * Note: the Army Creator server has to be running in order to start this monitor or else the {@link ServerSocket} will
 * not be created.
 * 
 * @author <a href="mailto:daniel.mfreitas@gmail.com">Daniel Freitas</a>
 */
public class SocketServerShutdownMonitor extends Thread implements ShutdownMonitor {

    private ServerSocket shutdownServerSocket;
    private final ArmyCreatorServer server;

    public SocketServerShutdownMonitor(ArmyCreatorServer server) {
        this.server = server;
        setDaemon(true);
        setName("ShutdownMonitor");
    }

    /**
     * @see com.googlecode.armycreator.server.ShutdownMonitor#startMonitoring()
     */
    public void startMonitoring() {

        try {
            shutdownServerSocket = new ServerSocket(3380, 1, InetAddress.getByName("127.0.0.1"));
        } catch (Exception e) {
            throw new RuntimeException("Unable to start shutdown monitor.", e);
        }

        this.start();
    }

    @Override
    public void run() {
        Socket clientSocket;
        String shutdownCommand;

        try {
            while (server.isRunning()) {
                clientSocket = shutdownServerSocket.accept();
                BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                shutdownCommand = reader.readLine();

                reader.close();
                clientSocket.close();

                if (shutdownCommand.equals("SHUTDOWN")) {
                    shutdownMessageReceived();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Shutdowns the Army Creator server if it is in running state. Ignores the event if the server is on any other
     * state.
     * 
     * @see com.googlecode.armycreator.server.ShutdownMonitor#shutdownMessageReceived()
     */
    @Override
    public void shutdownMessageReceived() {

        try {
            if (server.isRunning()) {
                server.shutdown();
            }
        } catch (Exception e) {
            throw new UnsupportedOperationException("The monitor was unable to stop the Army Creator server instance.",
                    e);
        }
    }
}
